package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"syscall"
)

var (
	n      int
	ip     string
	port   int
	cmdStr string
)

func init() {
	flag.IntVar(&n, "n", 5, "number of processes to keep")
	flag.StringVar(&ip, "i", "127.0.0.1", "ip address to bind")
	flag.IntVar(&port, "p", 9000, "port to bind, default is 9000")
	flag.StringVar(&cmdStr, "c", "", "Commands to be run, (this is require)")
	flag.Parse()
}

func main() {
	if cmdStr == "" {
		errLog := log.New(os.Stdout, "【error】", log.Lshortfile)
		errLog.Printf("err : please input Commands to be run")
		return
	}

	for i := 0; i < n; i++ {
		go func() {
			for {
				cmd := startPos()
				cmd.Wait()
			}
		}()
	}

	select {}
}

func startPos() *exec.Cmd {
	//cmd := exec.Command("E:\\wnmp\\php\\php-cgi.exe", "-b", "127.0.0.1:9000")
	cmd := exec.Command(cmdStr, "-b", fmt.Sprintf("%s:%d", ip, port))
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}

	if e := cmd.Start(); e != nil {
		log.Printf("exec failt to app : %s\n", e)
	}
	return cmd
}
